const { users, userIndex } = require("../data/index");
exports = module.exports = {
  getAllUsers: () => {
    return users;
  },
  add: (name) => {
    // 找到最后一个用户的ID，往后顺延
    userIndex.index += 1;
    const u = {
      id: userIndex.index,
      name,
    };
    users.push(u);
    return u;
  },
  update: (id, name) => {
    const index = users.findIndex(u => u.id === parseInt(id));
    if (index > -1) {
      users[index].name = name;
      return users[index];
    } else {
      throw new Error("User not found");
    }
  },
  delete: (id) => {
    const index = users.findIndex(u => u.id === parseInt(id));
    if (index > -1) {
      users.splice(index, 1);
    } else {
      throw new Error("User not found");
    }
  },
  getUserById: (id) => {
    return users.find(u => u.id === parseInt(id));
  },
}